<template>
  <view class="zh-shop-shopping-cart" v-if="show">
	<view class="no-shopping" v-if="shoppingCartData.total === 0">
		<view class="box">
			<text>购物车已清空</text>
			<button class="btn" @click="navigateTo('/pages/shop/goodsList')">去商城逛逛</button>
		</view>
	</view>
	//#ifdef MP-WEIXIN
	<view class="setting display-flex justify-end" v-if="shoppingCartData.total > 0">
		<view @click="settingShoppingCart">
			<text v-if="settingData.status == 0">管理</text>
			<text v-else>完成</text>
		</view>
	</view>
	//#endif
	<template v-if="shoppingCartData.total > 0">
		<view class="section" v-for="(topItem, index) in shoppingCartData.list" :key="topItem.spckmc">
			<view class="top display-flex justify-between align-center">
				<view class="display-flex align-center">
					<u-checkbox :sizePercent="0.9" color="#1769ff" :checked="topItem.checked" @change="selectDatas($event, index)"></u-checkbox>
					<text class="title">中恒纺织交易市场（广东）有限公司</text>
				</view>
				<text class="stock">{{ topItem.spckmc }}</text>
			</view>
			<view class="bottom">
				<view class="item display-flex" v-for="(item, index2) in topItem.list" :key="item.id">
					<u-checkbox :sizePercent="0.9" :checked="item.checked" @change="selectOneData($event, index, index2)" color="#1769ff"></u-checkbox>
					<view class="thumbnail">
						<template  v-for="(file, fileIndex) in item.wpggAFileDataList" :key="file.id">
							<image :src="util.previewImg(file.url)" v-if="fileIndex == 0" mode="aspectFit" /> 
						</template>
					</view>
					<view class="right flex">
						<view>{{ item.spzs }}</view>
						<view class="tags display-flex flex-wrap">
							<text class="tags-right" v-if="item.wpggA">{{ item.wpggA }}</text>
							<text class="tags-right" v-if="item.spcd">{{ item.spcd }}</text>
							<text class="tags-right" v-if="item.spckmc">{{ item.spckmc }}</text>
						</view>
						<view class="content display-flex justify-between align-center">
							<view class="content-left display-flex">
								<text class="font-FF661B font-26">{{ item.price?'¥' + item.price:'电议' }}</text>
								<text class="font-24 ml-5" v-if="item.price">/吨</text>
							</view>
							<view class="content-right display-flex align-center">
								<view class="content-right-box" @click="openWeightPopup(item)">{{ item.weight }}</view>
								<text  class="font-24 ml-10">吨</text>
							</view>
						</view>
						<view class="sub-total pull-right">
							<text class="font-24">小计：</text>
							<text class="font-FF661B font-28">¥{{ item.subtotal }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</template>
	<template v-if="shoppingCartData.total > 0">
		<view class="bottom-fixed display-flex justify-between align-center" v-if="settingData.status == 0">
			<view class="display-flex flex">
				<u-checkbox name="全选" fontSize="26" :sizePercent="0.9" color="#1769ff" :checked="allChecked" @change="selectAll($event)"></u-checkbox>
				<view class="ml-40">
					<view class="font-302D2D font-26">
						<text>共</text>
						<text class="font-FF661B">{{ getSumList.allSpjs }}</text>
						<text>件,</text>
						<text class="font-FF661B">{{ getSumList.weight }}</text>
						<text>吨</text>
					</view>
					<view class="font-302D2D font-26 mt-15">
						<text>合计：</text>
						<text class="font-FF661B font-28">¥{{ getSumList.subtotal }}</text>
					</view>
				</view>
			</view>
			<button class="app-primary-button" hover-class="app-primary-button-active" :style="bottomBtnStyle" @click="settlement">结算</button>
		</view>
		<view v-else class="bottom-fixed display-flex justify-between align-center">
			<view class="flex">
				<u-checkbox name="全选" fontSize="26" :sizePercent="0.9" color="#1769ff" :checked="allChecked" @change="selectAll($event)"></u-checkbox>
			</view>
			<button class="app-primary-button" hover-class="app-primary-button-active" :style="bottomBtnStyle" @click="deleteSelect">删除</button>
		</view>
	</template>
	<weight-edit-popup :show="showWeightPopup" :data="shoppingCartData.item" @close="closeWeightPopup" @sure="shoppingCartWeightSure"></weight-edit-popup>
  </view>
</template>

<script setup lang="ts">
	import { reactive, ref, computed, watch } from 'vue'
	import { goods } from '@/api'
	import { util, tip, nav, system } from '@/utils'
	import { Digit } from '@/enum/digit'
	import type { ShoppingCartData } from '@/@type/goods'
	import { onLoad, onShow, onPullDownRefresh, onNavigationBarButtonTap } from '@dcloudio/uni-app'
	import weightEditPopup from '@/pages/shop/components/weight-edit-popup'
	
	const allChecked = ref(true)
	const showWeightPopup = ref(false)
	const show = ref(false)
	const bottomBtnStyle = reactive({
		width:uni.upx2px(200) + 'px'
	})
	const shoppingCartData: any = reactive({
		query:{noJump:true},
		list:[],
		total:'',
		item:{},
		selection:[],
		delQuery:{
			ids:[],
		},
		delTotal:0,
	})
	const settingData = reactive({
		status:-1
	})
	
	onLoad(() => {
		tip.showLoading('加载中...')
	})
	
	onShow(() => {
		if(!nav.isLogin()) {
			uni.reLaunch({
				url:'/pages/auth/login'
			})
			system.setTabBarBadge({
			  index: 2,
			  text: '0'
			})
		} else {
			show.value = true
			shoppingCart()
		}
		tip.hideLoading()
	})
	
	onPullDownRefresh(() => {
		refresh()
		setTimeout(function () {
			uni.stopPullDownRefresh()
		}, 1000)
	})
	//#ifdef APP-PLUS
	const pages = getCurrentPages();
	const page: any = pages[pages.length - 1]
	const webView = page.$getAppWebview()
	onNavigationBarButtonTap((e:any) => {
		settingData.status = settingData.status === 0?1:0
	})
	watch(() => settingData.status, (newData:any) => {
		if(newData === 0) {
			webView.setTitleNViewButtonStyle(0,{
				"float":"right",
				"fontSize":"14",
				"text":"\ue679 管理",
				"fontSrc":"/static/iconfonts/iconfont.ttf",
				"width":"60px"
			})
		} else if(newData === 1) {
			webView.setTitleNViewButtonStyle(0,{
				"float":"right",
				"fontSize":"14",
				"text":"\ue679 完成",
				"fontSrc":"/static/iconfonts/iconfont.ttf",
				"width":"60px"
			})
		} else {
			webView.setTitleNViewButtonStyle(0,{
				"width":"0"
			})
		}
	})
	//#endif
	const refresh = () => {
		//allChecked.value = false
		//settingData.status = 0
		shoppingCart()
	}
	const getSumList = computed(() => {
		const selection:any = []
		const selections = shoppingCartData.list
		selections.map((item:any) => {
			item.list.map((item1:any) => {
				if(item1.checked) {
					selection.push(item1)
				}
			})
		})
		let weight = 0
		let subtotal = 0
		let allSpjs = 0
		
		for(let i in selection) {
			const upShelvesWeight = selection[i].upShelvesWeight?selection[i].upShelvesWeight:0
			const upShelvesNum = selection[i].upShelvesNum?selection[i].upShelvesNum:0
			const weight1 = selection[i].weight?selection[i].weight:0
			const subtotal1 = selection[i].subtotal?selection[i].subtotal:0
			const spjs = Number((upShelvesNum * weight1 / upShelvesWeight).toFixed(Digit.num)) || 0
			weight = weight + selection[i].weight
			subtotal = subtotal + subtotal1
			allSpjs = allSpjs + spjs
		}
		
		return {
			weight: parseFloat(weight.toFixed(Digit.weight)),
			subtotal: parseFloat(subtotal.toFixed(Digit.amount)),
			allSpjs: parseFloat(allSpjs.toFixed(Digit.num))
		}
	})
	
	const shoppingCart = () => {
		goods.getShoppingCart(shoppingCartData.query).then((res:any) => {
			const data: any = res.data
			const spckmcArr: Array<string> = []
			const dataArr: Array<{spckmc:string, list:any}> = []
			for(let i in data) {
				if(!spckmcArr.includes(data[i].spckmc)) {
					spckmcArr.push(data[i].spckmc)
				}
			}
			for(let i in spckmcArr) {
				let obj: any = {spckmc:spckmcArr[i], checked:true, list:[]}
				for(let j in data) {
					if(spckmcArr[i] == data[j].spckmc) {
						data[j].checked = true
						data[j].price = data[j].price?data[j].price:0
						data[j].subtotal = data[j].subtotal?data[j].subtotal:0
						obj.list.push(data[j])
					}
				}
				dataArr.push(obj)
			}
			allChecked.value = true
			shoppingCartData.list = dataArr
			shoppingCartData.total = data.length || 0
			settingData.status = shoppingCartData.total?settingData.status === -1?0:settingData.status: -1
			const len = data.length > 9?'9+': data.length.toString()
			system.setTabBarBadge({
			  index: 2,
			  text: len
			})
		})
	}
	
	const shoppingCartWeightSure = (data:any) => {
		data.id = shoppingCartData.item.id
		goods.setShoppingCartWeight(data).then((res:any) => {
			refresh()
			changeWeightPopup()
			tip.showToast('修改成功！')
			
		})
	}
	
	const selectDatas = (value:string, index:number) => {
		const selections = shoppingCartData.list
		let checked = value.length > 0?true:false
		let allCheck = true
		const item = selections[index]
		item.checked = checked
		if(item.list) {
			item.list.map((item1:any) => {
				item1.checked = checked
			})
		}
		selections.map((item:any) => {
			if(!item.checked) return allCheck = false
			if(item.list) {
				item.list.map((item1:any) => {
					if(!item1.checked) return allCheck = false
				})
			}
		})
		allChecked.value = allCheck
	}
	
	const selectOneData = (value:string, index:number, index2:number) => {
		const selections = shoppingCartData.list
		let checked = value.length > 0?true:false
		selections[index].list[index2].checked = checked
		let allCheck = true
		let checks = true
		selections[index].list.map((item:any) => {
			if(!item.checked) return checks = false
		}) 
		selections[index].checked = checks
		selections.map((item:any) => {
			if(!item.checked) return allCheck = false
			if(item.list) {
				item.list.map((item1:any) => {
					if(!item1.checked) return allCheck = false
				})
			}
		})
		allChecked.value = allCheck
	}
	
	const selectAll = (value:any) => {
		const selections = shoppingCartData.list
		if(selections && selections.length === 0) return tip.showToast('没有数据！')
		let checked = value.length > 0?true:false
		selections.map((item:any) => {
			item.checked = checked
			if(item.list) {
				item.list.map((item1:any) => {
					item1.checked = checked
				})
			}
		})
		allChecked.value = checked
	}
	
	const settlement = () => {
		if(nav.hasAppRole()) {
			const selections = shoppingCartData.list
			shoppingCartData.selection = []
			selections.map((item:any) => {
				item.list.map((item1:any) => {
					if(item1.checked) {
						item1.num = (item1.weight * 1000 / item1.spjsl).toFixed(Digit.num)
						shoppingCartData.selection.push(item1)
					}
				})
			})
			if(shoppingCartData.selection && shoppingCartData.selection.length == 0) return tip.showToast('请先选择购物单')
			navigateTo('/pages/shop/shoppingCartSure?info=' + encodeURIComponent(JSON.stringify(shoppingCartData.selection)))
		}	
	}
	
	const deleteSelect = () => {
		const selections = shoppingCartData.list
		shoppingCartData.delQuery.ids = []
		shoppingCartData.delTotal = 0
		selections.map((item:any) => {
			item.list.map((item1:any) => {
				if(item1.checked) {
					shoppingCartData.delQuery.ids.push(item1.id)
					shoppingCartData.delTotal++
				}
			})
		})
		if(shoppingCartData.total > 0 && shoppingCartData.delTotal <= 0) return tip.showToast('请选择要删除的商品') 
		tip.confirm('确定将已选中的' + shoppingCartData.delTotal + '件商品删除吗？').then(() => {
			goods.setShoppingCartDel(shoppingCartData.delQuery.ids).then(() => {
				refresh()
				tip.showToast('已成功删除商品')
			})
		})
		
	}
	
	const settingShoppingCart = () => {
		settingData.status = settingData.status == 0?1:0
	}
	
	const openWeightPopup = (item:any) => {
		shoppingCartData.item = item
		changeWeightPopup()
	}
	
	const closeWeightPopup = () => {
		changeWeightPopup()
	}
	
	const changeWeightPopup = () => {
		showWeightPopup.value = !showWeightPopup.value
	}
	
	const redirectTo = (url:string) => {
		uni.redirectTo({url:url})
	}
	
	const navigateTo = (url:string) => {
		uni.navigateTo({url:url})
	}
	
</script>

<style lang="scss" scoped>
	.zh-shop-shopping-cart {
		padding-bottom:210rpx;
		.no-shopping {
			padding-top:350rpx;
			.box {
				text-align: center;
				text {
					font-size:28rpx;
					color:#666;
				}
				.btn {
					width:200rpx;
					height:75rpx;
					line-height:75rpx;
					border-radius: 40rpx;
					color:$uni-color-primary;
					text-align: center;
					background-color: #fff;
					font-size:28rpx;
					border:1rpx solid $uni-color-primary;
					margin-top:20rpx;
				}
			}
		}
		.setting {
			background-color:$uni-bg-card-color;
			padding:20rpx 30rpx;
			font-size:24rpx;
		}
		.section {
			background-color: $uni-bg-card-color;
			padding:40rpx 30rpx 0rpx;
			margin-top: 20rpx;
			.top {
				.title {
					font-size: $uni-font-size-30;
					color:$uni-text-color-light-black;
					margin-left: 20rpx;
					font-weight: bold;
				}
				.stock {
					font-size:$uni-font-size-sm;
					color:$uni-text-color-dark-grey;
					
				}
			}
			.bottom {
				.item:nth-child(n + 2) {
					border-top: 1rpx solid $uni-border-color;
				}
				.item {
					padding: 40rpx 0;
					.thumbnail {
						width: 160rpx;
						height: 160rpx;
						background: #FFFFFF;
						border: 1rpx solid #EEEEEE;
						border-radius: 10rpx;
						text-align:center;
						margin-left: 20rpx;
						image {
							width: 100%;
							height:100%;
						}
					}
					.right {
						margin-left:30rpx;
						.tags {
							margin-top: 20rpx;
							.tags-right {
								text-align:center;
								color:#666666;
								background-color:#F5F6F8;
								padding:0 17rpx;
								height:34rpx;
								line-height: 34rpx;
								font-size: 22rpx;
								margin-right:10rpx;
								border-radius: 6px;
							}
							
						}
						.content {
							margin-top: 25rpx;
							&-right {
								&-box {
									width: 155rpx;
									height: 59rpx;
									border: 1rpx solid #DCDCDC;
									border-radius: 8rpx;
									font-size:26rpx;
									line-height:59rpx;
									color:$uni-text-color-light-black;
									padding-left:28rpx;
								}
							}
						}
						.sub-total {
							margin-top: 20rpx;
						}
					}
				}
			}
		}
		.bottom-fixed {
			background-color: #fff;
			position: fixed;
			bottom:0;
			left:0;
			right:0;
			padding: 20rpx 30rpx;
			.button {
				width: 190rpx;
				height: 88rpx;
			}
		}
	}
</style>

